import '../css/login.module.css'
import '../App.css'
import { Form, Input } from 'antd-mobile'
import { Button, Space,Toast } from 'antd-mobile'
import { list } from '../api/index.ts'
import { useNavigate } from 'react-router-dom'
import { useEffect } from 'react'

export default function Login() {
    const [form] = Form.useForm();
    const navigate = useNavigate(); // 替换replace，使用react-router-dom的useNavigate钩子

    // 表单验证规则
    const formRules = {
        username: [
            {
                required: true,
                message: '请输入手机号/用户名/邮箱',
                trigger: ['onBlur', 'onChange']
            },
            {
                validator: (rule, value) => {
                    // 支持手机号、邮箱或用户名（3-20位字符）
                    const phoneReg = /^1[3-9]\d{9}$/;
                    const emailReg = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
                    const usernameReg = /^[\w\u4e00-\u9fa5]{3,20}$/;

                    if (value && !(phoneReg.test(value) || emailReg.test(value) || usernameReg.test(value))) {
                        return Promise.reject('请输入有效的手机号、邮箱或3-20位用户名');
                    }
                    return Promise.resolve();
                },
                trigger: ['onBlur']
            }
        ],
        password: [
            {
                required: true,
                message: '请输入密码',
                trigger: ['onBlur', 'onChange']
            },
            {
                min: 6,
                max: 20,
                message: '密码长度需在6-20位之间',
                trigger: ['onBlur']
            },
            {
                validator: (rule, value) => {
                    // 密码强度校验（至少包含字母和数字）
                    const strongReg = /^(?=.*[A-Za-z])(?=.*\d).+$/;
                    if (value && !strongReg.test(value)) {
                        return Promise.reject('密码需同时包含字母和数字');
                    }
                    return Promise.resolve();
                },
                trigger: ['onBlur']
            }
        ]
    };

    // 处理登录逻辑
    const handleLogin = async () => {
        try {
            // 表单验证
            const values = await form.validateFields();

            // 调用登录接口
            const res = await list({
                tel: values.username,
                password: values.password
            });


            console.log('登录接口返回结果：', res);

            if (res.code === 1 && res.data?.token) {
                // 登录成功处理
                localStorage.setItem('token', res.data.token);
                localStorage.setItem('userInfo', JSON.stringify(res.data));
                localStorage.setItem('uid', JSON.stringify(res.data.id));

                // 获取跳转前的路径，若无则跳转到首页
                const fromPath = sessionStorage.getItem('redirectPath') || '/index';
                sessionStorage.removeItem('redirectPath');
                    Toast.show('登陆成功');

                // 延迟跳转，确保提示能显示
                setTimeout(() => {
                    navigate(fromPath, { replace: true });
                }, 500);
            } else {
                console.error('登录失败：', res);
            }
        } catch (error) {
            console.error('登录请求失败：', error)
        }
    };

    // 页面加载时保存当前路径，用于登录后返回
    useEffect(() => {
        const currentPath = window.location.pathname;
        if (currentPath !== '/login') {
            sessionStorage.setItem('redirectPath', currentPath);
        }
    }, []);

    return (
        <>
            <div className='background'>
                <div className='margin'>
                    <div className='login'>登录</div>

                    {/* 表单增加验证规则 */}
                    <Form
                        layout='vertical'
                        form={form}
                        rules={formRules}
                        initialValues={{ username: '', password: '' }}
                    >
                        <Form.Item
                            name='username'
                            className='form-item'
                        >
                            <Input
                                placeholder='请输入手机号/用户名/邮箱'
                                clearable
                                maxLength={50}
                                className='input-field'
                            />
                        </Form.Item>

                        <Form.Item
                            name='password'
                            className='form-item'
                        >
                            <Input
                                placeholder='请输入密码'
                                clearable
                                type='password'
                                maxLength={20}
                                className='input-field'
                            />
                        </Form.Item>
                    </Form>

                    <div className='inputBottom'>
                        <div
                            className='link-text'
                            onClick={() => navigate('/forgot-password')}
                        >
                            忘记密码
                        </div>
                        <div
                            className='link-text'
                            onClick={() => navigate('/sms-login')}
                        >
                            免密码登录
                        </div>
                    </div>

                    <Space wrap className='btn-container'>
                        <Button
                            block
                            shape='rounded'
                            color='primary'
                            className='login-btn'
                            onClick={handleLogin}
                        >
                            登录
                        </Button>
                    </Space>

                    <div
                        className='nozhanghao link-text'
                        onClick={() => navigate('/register')}
                    >
                        没有账号，去注册
                    </div>

                    <div style={{ height: '50px' }}></div>
                    <div className='nozhanghao'>第三方账号登录</div>
                    <div style={{ height: '20px' }}></div>

                    <div className='weixin'>
                        <img
                            src="https://img.xiaopiu.com/userImages/img17526318aceb43840.png"
                            alt="微信登录图标"
                            style={{ width: '40px', height: '40px' }}
                            className='third-party-icon'
                        />
                    </div>

                    <div style={{ height: '20px' }}></div>
                    <div
                        className='nozhanghao agreement-text'
                        onClick={() => navigate('/user-agreement')}
                    >
                        登录即同意《用户服务协议》
                    </div>
                </div>
            </div>
        </>
    )
}
